
import 'package:flame/collisions.dart';
import 'package:flame/game.dart';
import 'package:flame/events.dart';
import 'package:flame/input.dart';
import 'package:flame/sprite.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import '../component.dart';

class Game3 extends FlameGame with KeyboardEvents, TapDetector, PanDetector {
  late final HeroComponent player;
  late final Monster monster;
  late final RectangleHitbox box;

  @override
  Future<void> onLoad() async {
    const String src = 'adventurer/animatronic.png';
    await images.load(src);
    var image = images.fromCache(src);
    SpriteSheet sheet =
        SpriteSheet.fromColumnsAndRows(image: image, columns: 13, rows: 6);
    int frameCount = sheet.rows * sheet.columns;
    List<Sprite> sprites = List.generate(frameCount, sheet.getSpriteById);
    SpriteAnimation animation =
        SpriteAnimation.spriteList(sprites, stepTime: 1 / 24, loop: true);
    Vector2 monsterSize = Vector2(64, 64);
    final double pY = size.y / 2;
    final double pX = size.x / 2;
    monster = Monster(
        animation: animation, size: monsterSize, position: Vector2(pX, pY));
    player = HeroComponent();
    box = RectangleHitbox()..debugMode = false;
    player.add(box..debugMode = false);
    add(player);
    add(monster);
  }

  final double step = 10;

  double _counter = 0;

  @override
  void onTap() {
    _counter++;
    // player.rotateTo(_counter * pi / 2);
    monster.loss(50);
  }

  @override
  onTapCancel() {
    box.debugMode = false;
  }

  @override
  onTapDown(TapDownInfo info) {
    box.debugMode = true;
    box.debugColor = Colors.purple;
  }

  @override
  onTapUp(TapUpInfo info) {
    box.debugMode = false;
  }

  @override
  void onPanStart(DragStartInfo info) {}

  @override
  void onPanUpdate(DragUpdateInfo info) {
    player.move(info.delta.global);
  }

  @override
  void onPanEnd(DragEndInfo info) {
    box.debugMode = false;
  }

  @override
  void onPanCancel() {
    box.debugMode = false;
  }

  // 键盘事件
  @override
  KeyEventResult onKeyEvent(
      KeyEvent event, Set<LogicalKeyboardKey> keysPressed) {
    final isKeyDown = event is KeyDownEvent;
    if (event.logicalKey == LogicalKeyboardKey.keyY && isKeyDown) {
      player.flip(y: true);
    }
    if (event.logicalKey == LogicalKeyboardKey.keyX && isKeyDown) {
      player.flip(x: true);
    }
    if (event.logicalKey == LogicalKeyboardKey.keyW && isKeyDown) {
      player.move(Vector2(0, -step));
    }

    if (event.logicalKey == LogicalKeyboardKey.keyS && isKeyDown) {
      player.move(Vector2(0, step));
    }

    if (event.logicalKey == LogicalKeyboardKey.keyA && isKeyDown) {
      player.move(Vector2(-step, 0));
    }

    if (event.logicalKey == LogicalKeyboardKey.keyD && isKeyDown) {
      player.move(Vector2(step, 0));
    }

    return super.onKeyEvent(event, keysPressed);
  }
}
